#include "TransThread.h"
TransThread::TransThread(onTransFrameCB cbTransFrame){
    _bVideoTransCode = true;
    _cbTransFrame = cbTransFrame;
}
TransThread::~TransThread() {
    PushFrame(nullptr);
    wait();
}
void TransThread::PushFrame(const Frame::Ptr &frame_in){
    _frameCachedMtx.lock();
    _frameCached.push_back(frame_in);
    //printf("送进去一帧数据,当前大小:%lu\n",_frameCached.size());
    _frameCachedMtx.unlock();
    _sem.post();
    
}
void TransThread::start() {
    auto thrd = _thread_group.create_thread(bind(&TransThread::run, this));
    SetThreadName(thrd,"TransThread");//设置线程名称为转码线程
}
void TransThread::wait() {
    _thread_group.join_all();
}
void TransThread::run() {
    if(_bVideoTransCode) {
        if (!_pVideohandle) {
            InfoL << "Open h265 transcode handle";
            int width = 1920, height = 1080;
            try {
                _pVideohandle = InitTransCode("H265TRANSH264", width, height);
            } catch(std::exception e) {
                fprintf(stderr, "Called InitTransCode Error! Next send old type stream\n");//只有一次尝试的机会
                _bVideoTransCode = false;
                _pVideohandle = NULL;
            }
        }
    }
    while(true){
        Frame::Ptr frame = nullptr;
        _frameCachedMtx.lock();
        if(_frameCached.size() <= 0) {
            //printf("等待帧,当前大小:%lu\n",_frameCached.size());
            _frameCachedMtx.unlock();
            _sem.wait();
            continue;
        }else{
            //printf("拿到帧,当前大小:%lu\n",_frameCached.size());
            frame = _frameCached.front();
            _frameCached.pop_front();
            _frameCachedMtx.unlock();
        }
        if(frame) {
             if(_bVideoTransCode) {
                int hasKeyFrame;
                unsigned int out_len = 0;
                uint8_t* videobuf = (uint8_t*)malloc(EASY_MAX_FRAME_LEN);
                uint32_t dts = 0;
                uint32_t pts = 0;
                //printf("执行转码,当前大小:%lu\n",frame->size());
                if (TransCodeWork(_pVideohandle, (uint8_t*)frame->data(),
                            frame->size(),frame->pts(),frame->dts(), videobuf, &out_len,&dts,&pts, &hasKeyFrame) > 0) {
                    _cbTransFrame(videobuf,out_len,dts,pts,hasKeyFrame);
                }
            }
        }else{
            //视为退出信号
            InfoL << "quit  h265 transcode thread";
            break;
        }
    }
    ReleaseTransCode(_pVideohandle);
    _pVideohandle = nullptr;
    InfoL << "h265 transcode thread quited";
}
